const http = require('http');
const fs = require('fs');
const path = require('path');

const server = http.createServer();

server.on('request', (req1, res1) => {    
    if (req1.url === '/') {
        //返回首页
        fs.readFile(path.join(__dirname, 'index.html'), (err, data) => {
            res1.end(data);
        })
    } else {
        const options = {
            host: 'localhost',
            port: 8888,
            path: req1.url,
            method: 'get',
            aa: 'bb'
        };

        // 
        const req = http.request(options, (res) => {
            console.log(2222);
            console.log(`状态码: ${res.statusCode}`);
            console.log(`响应头: ${JSON.stringify(res.headers)}`);
            // console.log(`响应体: ${res.bddy}`);
            // console.log(res);
            res.setEncoding('utf8');
            var html = '';
            res.on('data', (data) => {
                html += data;
            });
            res.on('end', () => {
                console.log(html);
                res1.end(html);
            });
        });

        // 测试响应头 
        req.setHeader('Content-Type', 'application/json');
        req.setHeader('aa', 'bb');
        req.setHeader('cc', 'dd');

        // 错误处理
        req.on('error', (e) => {
            console.error(`请求遇到问题: ${e.message}`);
        });

        req.end();
    }

    // 
    console.log(`浏览器请求：${req1.url}--${req1.method}`);
    console.log('http://localhost:9999 服务器已启动');




});



server.listen(9999, () => {
    console.log('http://localhost:9999 服务器已启动');
});